package com.lxl.jwt1.config;

import com.lxl.jwt1.service.UserServiceImpl;
import com.lxl.jwt1.utils.MyAuthenticationEntryPoint;
import com.lxl.jwt1.utils.TokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class SpringSecurityConfig {

    @Autowired
    com.lxl.jwt1.utils.MyAccessDeniedHandler MyAccessDeniedHandler;
    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager manager= new InMemoryUserDetailsManager();
//
//
//        //考虑到一般数据库存的是密文
//        UserDetails user1= User.withUsername("admin").password(passwordEncoder().encode("123")).roles("admin").build();
//        UserDetails user2= User.withUsername("boss").password(passwordEncoder().encode("123")).roles("boss").build();
//        manager.createUser(user1);
//        manager.createUser(user2);
//        return manager;
//    }
    //白名单
    @Bean
    WebSecurityCustomizer webSecurityCustomizer(){
        return web -> web.ignoring().requestMatchers("/login");
    }
    //配置过滤器链条   授权
    @Bean
    SecurityFilterChain filterChain(HttpSecurity security) throws Exception {

        security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//session策略设置成无状态——因为我们是前后分离项目，不用session存登录状态
                .and()
                .authorizeRequests()//如果你使用了authorizeHttpRequests，那么使用withObjectPostProcessor去配置我们自定义的元数据源和权限决策配置时是无效的，因为不会进去
                .requestMatchers("/admin").hasAuthority("admin")
                .requestMatchers("/boss").hasAuthority("boss")
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(MyAccessDeniedHandler)
                .authenticationEntryPoint(myAuthenticationEntryPoint)
                .and()
                .addFilterBefore(new TokenFilter(new UserServiceImpl()), UsernamePasswordAuthenticationFilter.class);
        return security.build();

    }
}